<template>
  <div class="dashboard">
    <!-- 概览卡片 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :span="6">
        <el-card class="overview-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon cache">
              <el-icon><DataLine /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">缓存命中率</div>
              <div class="card-value">{{ (cacheHitRate * 100).toFixed(1) }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="overview-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon memory">
              <el-icon><Monitor /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">内存使用率</div>
              <div class="card-value">{{ memoryUsage.toFixed(1) }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="overview-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon requests">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">请求总数</div>
              <div class="card-value">{{ performanceMetrics.requestCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="overview-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon latency">
              <el-icon><Timer /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">平均延迟</div>
              <div class="card-value">{{ performanceMetrics.averageLatency.toFixed(0) }}ms</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-section">
      <el-col :span="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>系统性能趋势</span>
              <el-button size="small" @click="refreshPerformanceChart">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <div class="chart-container">
            <performance-chart :data="performanceData" :loading="chartsLoading" />
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>热点数据分布</span>
              <el-button size="small" @click="refreshHotKeysChart">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <div class="chart-container">
            <hot-keys-chart :data="hotKeysData" :loading="chartsLoading" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 系统状态 -->
    <el-row :gutter="20" class="status-section">
      <el-col :span="8">
        <el-card class="status-card" shadow="hover">
          <template #header>ID生成器状态</template>
          <div class="status-content">
            <el-descriptions :column="1" size="small">
              <el-descriptions-item label="实例标识">
                <el-tag size="small">{{ idGeneratorStats?.instanceKey || 'N/A' }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="当前ID">
                {{ idGeneratorStats?.currentId || 0 }}
              </el-descriptions-item>
              <el-descriptions-item label="最大ID">
                {{ idGeneratorStats?.maxId || 0 }}
              </el-descriptions-item>
              <el-descriptions-item label="剩余ID">
                <el-tag :type="remainingIdTagType">
                  {{ idGeneratorStats?.remainingIds || 0 }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="status-card" shadow="hover">
          <template #header>缓存状态</template>
          <div class="status-content">
            <el-descriptions :column="1" size="small">
              <el-descriptions-item label="缓存大小">
                {{ cacheStats?.size || 0 }} 条目
              </el-descriptions-item>
              <el-descriptions-item label="命中次数">
                {{ cacheStats?.hitCount || 0 }}
              </el-descriptions-item>
              <el-descriptions-item label="未命中次数">
                {{ cacheStats?.missCount || 0 }}
              </el-descriptions-item>
              <el-descriptions-item label="淘汰次数">
                {{ cacheStats?.evictionCount || 0 }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="status-card" shadow="hover">
          <template #header>系统资源</template>
          <div class="status-content">
            <el-descriptions :column="1" size="small">
              <el-descriptions-item label="总内存">
                {{ systemStats?.totalMemoryMB || 0 }} MB
              </el-descriptions-item>
              <el-descriptions-item label="已用内存">
                {{ systemStats?.usedMemoryMB || 0 }} MB
              </el-descriptions-item>
              <el-descriptions-item label="活跃线程">
                {{ systemStats?.activeThreads || 0 }}
              </el-descriptions-item>
              <el-descriptions-item label="运行时间">
                {{ formatUptime(systemStats?.upTimeSeconds) }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useSystemStore } from '../../store/pinia_stores.js'
// 暂时注释掉不存在的导入
// import { useKvStore } from '@/stores/kv'
import PerformanceChart from '../../components/charts/performanceChart.vue'
import HotKeysChart from '../../components/charts/HotKeysChart.vue'

const systemStore = useSystemStore()
// 暂时注释掉不存在的store
// const kvStore = useKvStore()

// 响应式数据
const chartsLoading = ref(false)
const performanceData = ref([])
const hotKeysData = ref([])
let refreshInterval = null

// 计算属性
const cacheHitRate = computed(() => systemStore.cacheHitRate)
const memoryUsage = computed(() => systemStore.memoryUsage)
const performanceMetrics = computed(() => systemStore.performanceMetrics)

const statistics = computed(() => systemStore.statistics)
const cacheStats = computed(() => statistics.value.cacheStats)
const idGeneratorStats = computed(() => statistics.value.idGeneratorStats)
const systemStats = computed(() => statistics.value.systemStats)

const remainingIdTagType = computed(() => {
  const remaining = idGeneratorStats.value?.remainingIds || 0
  if (remaining < 100) return 'danger'
  if (remaining < 1000) return 'warning'
  return 'success'
})

// 方法
const loadDashboardData = async () => {
  try {
    await systemStore.loadStatistics()
    // 暂时注释掉不存在的方法调用
    // await kvStore.loadHotKeys(10)
    
    // 模拟性能数据(实际应用中应从后端获取)
    generatePerformanceData()
    // 暂时注释掉不存在的方法调用
    // updateHotKeysData()
  } catch (error) {
    console.error('加载仪表板数据失败:', error)
  }
}

const generatePerformanceData = () => {
  const now = new Date()
  const data = []
  
  for (let i = 23; i >= 0; i--) {
    const time = new Date(now.getTime() - i * 60 * 60 * 1000)
    data.push({
      time: time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
      requests: Math.floor(Math.random() * 1000) + 500,
      latency: Math.floor(Math.random() * 50) + 10,
      errors: Math.floor(Math.random() * 10)
    })
  }
  
  performanceData.value = data
}

const updateHotKeysData = () => {
  // 暂时使用模拟数据
  hotKeysData.value = [
    { key: 'user:1001', accessCount: 120, id: 1 },
    { key: 'product:2001', accessCount: 98, id: 2 },
    { key: 'session:3001', accessCount: 85, id: 3 }
  ]
}

const refreshPerformanceChart = async () => {
  chartsLoading.value = true
  try {
    generatePerformanceData()
  } finally {
    chartsLoading.value = false
  }
}

const refreshHotKeysChart = async () => {
  chartsLoading.value = true
  try {
    await kvStore.loadHotKeys(10)
    updateHotKeysData()
  } finally {
    chartsLoading.value = false
  }
}

const formatUptime = (seconds) => {
  if (!seconds) return '0秒'
  
  const days = Math.floor(seconds / 86400)
  const hours = Math.floor((seconds % 86400) / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  
  if (days > 0) return `${days}天${hours}小时`
  if (hours > 0) return `${hours}小时${minutes}分钟`
  return `${minutes}分钟`
}

// 生命周期
onMounted(() => {
  loadDashboardData()
  
  // 定期刷新数据(每30秒)
  refreshInterval = setInterval(loadDashboardData, 30000)
})

onUnmounted(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
})
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.overview-cards {
  margin-bottom: 20px;
}

.overview-card {
  height: 120px;
}

.card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.card-icon.cache {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-icon.memory {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-icon.requests {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.card-icon.latency {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 320px;
}

.status-section {
  margin-bottom: 20px;
}

.status-card {
  height: 280px;
}

.status-content {
  padding: 10px 0;
}
</style>